<template>
  <div id="monopoly-game" class="game-container">
    <h1>区块链大富翁游戏</h1>
    <div class="player-info">
      <p>当前积分: <span class="score">{{ playerInfo.score }}</span></p>
      <p>当前位置: <span class="position">{{ playerInfo.position }}</span></p>
    </div>
    <van-button
      square
      style="background: #51915d; color: white; border-radius: 8px;"
      @click="rollDice"
      :loading="isRolling"
      class="dice-btn"
      title="点击掷骰子开始游戏"
    >
      {{ isRolling? "掷骰子中..." : "🎲掷骰子🎲" }}
    </van-button>
    <van-button
      style="background: #ca3737; color: white; border-radius: 8px;"
      @click="clearGame"
      class="clear-btn"
      title="点击清除游戏缓存，重置游戏数据"
    >
    🧹清除缓存🧹
    </van-button>
    <p class="event-message">{{ eventMessage }}</p>
    <div class="game-board">
      <div
        v-for="(tile, index) in board"
        :key="index"
        :class="['board-tile', { active: index === playerInfo.position, selected: index === lastSelected }]"
      >
        {{ tile }}
      </div>
    </div>
  </div>
</template>

<script>
import { contractInstance } from '../util';
import { createApp } from 'vue';
import { Button } from 'vant';

// 创建Vue应用实例并使用Vant的Button组件
const app = createApp();
app.use(Button);

export default {
  data() {
    return {
      playerInfo: {
        score: 0,
        position: 0,
      },
      eventMessage: '欢迎来到区块链大富翁游戏！🎮',
      board: ['起点', '奖励10分', '扣除5分', '奖励20分', '扣除10分', '机会格'],
      isRolling: false,
      lastSelected: null, // 记录上一次选中的方块
    };
  },
  methods: {
    async fetchPlayerInfo() {
      try {
        const accounts = await window.ethereum.request({
          method: 'eth_requestAccounts',
        });

        const result = await contractInstance.methods.getPlayerInfo().call({
          from: accounts[0],
        });

        this.playerInfo.score = result.score;
        this.playerInfo.position = result.position;
      } catch (error) {
        console.error('获取玩家信息失败:', error);
        this.eventMessage = '无法获取玩家信息，请重试！';
      }
    },
    async rollDice() {
      try {
        this.isRolling = true;
        const accounts = await window.ethereum.request({
          method: 'eth_requestAccounts',
        });

        await contractInstance.methods.rollDice().send({
          from: accounts[0],
          gas: 100000,
          gasPrice: 100000000, // 使用传统 gasPrice
        });

        // 监听智能合约事件
        contractInstance.once('DiceRolled', (error, event) => {
          if (error) {
            console.error('事件监听失败:', error);
            this.eventMessage = '掷骰子失败，请稍后再试！';
            return;
          }
          const { diceResult, newPosition, eventMessage } = event.returnValues;
          this.$set(this.playerInfo, 'position', newPosition); // 强制 Vue 更新
          this.eventMessage = `你掷出了 ${diceResult} 点！${eventMessage}`;
          this.lastSelected = newPosition; // 更新选中的方块
        });

        // 更新玩家信息
        await this.fetchPlayerInfo();

      } catch (error) {
        console.error('掷骰子失败:', error);
        this.eventMessage = '掷骰子失败，请检查网络连接。';
      } finally {
        this.isRolling = false;
      }
    },
    async clearGame() {
      try {
        const accounts = await window.ethereum.request({
          method: 'eth_requestAccounts',
        });

        // 调用智能合约的重置函数来清空玩家数据
        await contractInstance.methods.resetPlayerData().send({
          from: accounts[0],
          gas: 3000000,
          gasPrice: '20000000000', // 使用传统 gasPrice
        });

        // 更新前端状态
        this.playerInfo = { score: 0, position: 0 };
        this.eventMessage = '游戏已重置，积分和位置已清空！';
        this.lastSelected = null;

      } catch (error) {
        console.error('重置游戏失败:', error);
        this.eventMessage = '重置游戏失败，请检查网络连接。';
      }
    },
  },
  async mounted() {
    await this.fetchPlayerInfo();
  },
};
</script>

<style>
@import url('../../styles/global.css');

.game-container {
  --bg-color: #f0f0f075; /* 默认背景颜色，可外部修改 */
  background-color: var(--bg-color);
  text-align: center;
  margin: 20px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.player-info {
  font-size: 18px;
  margin-bottom: 20px;
}

.score {
  font-weight: bold;
  color: green;
}

.dice-btn {
  margin: 10px;
}

.clear-btn {
  margin: 10px;
}

.event-message {
  margin-top: 20px;
  font-size: 16px;
  color: #333;
}

.game-board {
  display: grid; /* 使用网格布局 */
  grid-template-columns: repeat(3, 1fr); /* 每行显示3个方块 */
  grid-template-rows: repeat(2, 1fr); /* 共两行 */
  grid-gap: 10px; /* 方块间隔 */
  justify-content: center;
  margin-top: 20px;
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.board-tile {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  font-size: 14px;
  text-align: center;
  transition: background-color 0.3s;
  background-color: #f9f9f9; /* 设置默认背景色 */
}

.board-tile.active {
  background-color: #007bff;
  color: white;
  font-weight: bold;
}

.board-tile.selected {
  background-color: #28a745;
  color: white;
  font-weight: bold;
}
</style>